package com.wuliu.dao.impl;

import com.wuliu.dao.UserDAO;
import com.wuliu.model.User;
import com.wuliu.util.Jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class UserDAOImpl implements UserDAO {
    @Override
    public void update(User user) {
        String sql = "update user set account = ?,password = ? ,name = ?,gender = ? where id = ?";
        try {
            Jdbc jdbc=new Jdbc();
            Connection connection=jdbc.connection();
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1,user.getAccount());
            statement.setString(2,user.getPassword());
            statement.setString(3,user.getName());
            statement.setString(4,user.getGender());
            statement.setInt(5,user.getId());
            statement.execute();
            statement.close();
            connection.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public User findByAccount(String account) {
        User user = null;
        try {
            Jdbc jdbc=new Jdbc();
            Connection connection=jdbc.connection();
            String sql = "select * from user where account = ?";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1,account);
            ResultSet set = statement.executeQuery();
            while (set.next()){
                Integer id = set.getInt("id");
                String password = set.getString("password");
                String name = set.getString("name");
                String gender = set.getString("gender");
                boolean admin=set.getBoolean("admin");
                user = new User(id,account,password,name,gender,admin);
            }
            set.close();
            statement.close();
            connection.close();
        }catch (Exception e){
            e.printStackTrace();
        }

        return user;
    }

    @Override
    public void add(User user) {
        try {
            Jdbc jdbc=new Jdbc();
            Connection connection=jdbc.connection();
            String sql = "insert into user values (null,?,?,?,?,?)";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1, user.getAccount());
            statement.setString(2, user.getPassword());
            statement.setString(3, user.getName());
            statement.setString(4, user.getGender());
            statement.setBoolean(5,user.isAdmin());
            statement.execute();
            statement.close();
            connection.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
